package com.xzp.blog.controller.base;


import com.xzp.blog.entity.dto.response.factory.GeneralJsonFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器基类
 * @author Xbear
 */

public class BaseController {


    protected GeneralJsonFactory generalJsonFactory;

    /**
     * 捕获异常 如果发生异常,则直接跳转到/error界面
     */
    @ExceptionHandler
    public String handleException(HttpServletRequest request,Exception e){
        return "/error";
    }

    /**
     * 给页面添加标题
     * @param model
     * @param title
     */
    public void setPageTitle(Model model,String title){
        model.addAttribute("title",title);
    }

    /**
     * 根据名称获取Session中的值
     * @param request
     * @param attrName
     * @return
     */
    public Object getSessionAttr(HttpServletRequest request,String attrName){
        return request.getSession().getAttribute(attrName);
    }

    /**
     * 向 Model 添加数据 这个方法控制器中经常会用到,所以用父类实现比较合理
     */
    public void addModelAtt(Model model, String attribute, Object value) throws Exception {
        if (null != value) {
            model.addAttribute(attribute, value);
        } else {
            throw new Exception();
        }
    }

    /**
     * 向 Session 中添加对象
     */
    public void addSessionAtrr(HttpServletRequest request, String attribute, Object value) {
        request.getSession().setAttribute(attribute,value);
    }


    /**
     * 返回 成功 json
     */
    public Object responseSimpleOK() {
        return generalJsonFactory.createSimpleResponse();
    }

    /**
     * 返回 失败 json
     */
    public Object responseSimpleError() {
        return generalJsonFactory.createSimpleErrorResponse();
    }


    }
